/*
 *  Copyright 2012 yura.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */
package org.opu.pc.security;

import java.security.MessageDigest;
import org.springframework.dao.DataAccessException;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import sun.misc.BASE64Encoder;

/**
 *
 * @author yura
 */
public final class PasswordServiceImpl implements PasswordEncoder {

    private BASE64Encoder base64Encoder = new BASE64Encoder();

    @Override
    public String encodePassword(String rawPass, Object salt) throws DataAccessException {
        return encrypt(rawPass);
    }

    @Override
    public boolean isPasswordValid(String encPass, String rawPass, Object salt) throws DataAccessException {
        return  encrypt(rawPass).equals(encPass);
    }

    private String encrypt(String rawPass) throws RuntimeException {
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("SHA-1"); //step 2
            md.update(rawPass.getBytes("UTF-8")); //step 3
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        byte[] raw = md.digest(); //step 4
        String hash = base64Encoder.encode(raw); //step 5
        return hash; //step 6
    }
}
